/** 
 * projectName:  
 * fileName:  
 * packageName:  
 * date: 
 * copyright(c) 2017-2020 xxx公司
 */
package cn.message.service.impl;

import java.io.File;
import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.itcast.mapper.adminMapper;
import cn.itcast.mapper.roleMapper;
import cn.itcast.pojo.admin;
import cn.itcast.pojo.adminExample;
import cn.itcast.pojo.permission;
import cn.itcast.pojo.role;
import cn.itcast.util.CookieUtil;
import cn.itcast.util.JwtUtil;
import cn.itcast.util.RedisUtil;
import cn.message.service.IPermissionService;
import cn.message.service.IRoleService;
import cn.message.service.adminService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**   
 * @title: userServiceImpl.java 
 * @package com.job.service.lmpl 
 * @description: TODO
 * @author: 欧阳辉
 * @date: 2019年1月25日 下午3:21:04 
 * @version: V1.0   
*/
@Service
@Slf4j
public class adminServiceImpl implements adminService {

	@Resource
	private IRoleService roleService;

	@Resource
	private IPermissionService permissionService;
	

	/*@Resource
    private RedisTemplate template;*/
	@Resource
	adminMapper adminMapper;

	@Resource
	roleMapper roleMapper;

	@Resource
	CookieUtil cookieUtil;





	@Override
	public boolean usernameChecked(String adminNickname) {
		boolean ischeck = true;
		adminExample aEx = new adminExample();
		adminExample.Criteria criteria = aEx.createCriteria();
		criteria.andAdminNicknameEqualTo(adminNickname);
		List<admin> admins = adminMapper.selectByExample(aEx);
		try {
			admins.get(0);
		} catch (Exception e) {
			ischeck = false;
		}
		return ischeck;
	}

	@Override
	public Map<String,Object> login(HttpServletResponse response,String adminNickname, String adminPassword,HttpSession session) {
//		//String token = UUID.randomUUID().toString();
//		//返回Map
//		Map<String,Object> map = new HashMap<String, Object>();
//		boolean islogin=true;
//		adminExample aEx = new adminExample();
//		adminExample.Criteria criteria = aEx.createCriteria();
//		criteria.andAdminNicknameEqualTo(adminNickname);
//		List<admin> admins = adminMapper.selectByExample(aEx);
//		if(!admins.isEmpty()) {
//			String password = admins.get(0).getAdminPassword();
//			if(adminPassword.equals(password)) {
//				//用户验证成功获取唯一标识符token
//				String token = JwtUtil.sign(adminNickname, admins.get(0).getAdminId());
//				//把token存入cookie中
//				CookieUtil.addCookie(response, "token", token, 1800);
//				//把token存入session中
//				session.setAttribute("token", token);
//				//设admin密码为空,转为json存入redis中
////				admins.get(0).setAdminPassword(null);
//				//JSONObject userjson = JSONObject.fromObject(admins.get(0));
//				//System.out.println("token:"+token+";userjson:"+userjson);
//				//以token为key存入redis中
//                //template.opsForValue().set(token,userjson);
//                //template.expire(token,1800, TimeUnit.SECONDS);
//				//redisUtil.set(token, userjson);
//				//redisUtil.expire(token, 1800);
//				//管理员数据返回前台
//				map.put("admin",admins.get(0));
//				map.put("islogin", islogin);
//				//System.out.println(template.opsForValue().get(token));
//				System.out.println(admins.get(0).getAdminNickname()+"登录成功");
//			}else {
//				islogin = false;
//				map.put("admin","");
//				map.put("isloginn", islogin);
//			}
//		}else {
//			islogin = false;
//			map.put("admin","");
//			map.put("isloginn", islogin);
//		}
//		return map;
// -------------------------------------------------------------------------------------------------
		adminExample aEx = new adminExample();
		adminExample.Criteria criteria = aEx.createCriteria();
		criteria.andAdminNicknameEqualTo(adminNickname);
		List<admin> admins = adminMapper.selectByExample(aEx);
		admin admin = admins.get(0);
		//根据管理员的id查询该管理员所有的角色
		List<role> roleList = roleService.getRoleByAdminId(admin.getAdminId());
		//把管理员所有角色的id存入到一个list中，目的是为了根据所有的角色id查询该管理员所有的权限
		ArrayList<Integer> roleIds = new ArrayList<>();
		for (role role : roleList) {
			System.out.println(role);
			roleIds.add(role.getRoleId());
		}

		//根据管理员所有的角色id查询该管理员所拥有的权限
		List<permission> permissionList = permissionService.getPermissionByRoleIds(roleIds);

		log.debug(permissionList.toString());

		HashSet<String> roleSet = new HashSet<>();
		HashSet<String> permissionSet = new HashSet<>();

		//此处如果多个角色都拥有某项权限，不会数据重复，内部用的是Set
		for (permission permission : permissionList) {
			permissionSet.add(permission.getPermission());
		}
		for (cn.itcast.pojo.role role : roleList) {
			roleSet.add(role.getRole());
		}

		//用户验证成功获取唯一标识符token
		String token = JwtUtil.sign(adminNickname, admin.getAdminId());
		//把token存入cookie中
		CookieUtil.addCookie(response, "token", token, 60*6000);
		//把token存入session中
		session.setAttribute("token", token);

		HashMap<String, Object> map = new HashMap<>();
		map.put("roleSet",roleSet);
		map.put("permissionSet",permissionSet);
		map.put("admin",admin);
		return map;
	}

	@Override
	public admin getUserByLoginName(String adminNickname) {
		adminExample aEx = new adminExample();
		adminExample.Criteria criteria = aEx.createCriteria();
		criteria.andAdminNicknameEqualTo(adminNickname);
		List<admin> admins = adminMapper.selectByExample(aEx);
		return admins.get(0);
	}

	@Override
	public boolean changeLoginState(Integer adminId,Integer state) {
		admin admin = new admin();
		admin.setAdminId(adminId);
		admin.setAdminState(state);
		adminMapper.updateByPrimaryKeySelective(admin);
		return true;
	}

	@Override
	public boolean edit(HttpServletResponse response, HttpSession session,String token) {
		boolean isedit = true;
		//清除cookie
		CookieUtil.removeCookie(response, "token");
		//清除session
		session.invalidate();
		//清空redis
		//redisUtil.del(token);
		//template.delete(token);
		return isedit;
		
	}

	@SuppressWarnings("null")
	@Override
	public admin getUserMsg(Integer adminId,String token) {
		//JSONObject ad = (JSONObject) template.opsForValue().get(token);
		admin admin = new admin();
		/*System.out.println(ad);
		if(StringUtils.isNotBlank(ObjectUtils.toString(ad))) {
			 admin= (admin) JSONObject.toBean(ad,admin.class);
			System.out.println(admin.toString());
		}else {*/
			admin = adminMapper.selectByPrimaryKey(adminId);
		//}
		return admin;
	}

	@Override
	public boolean updateAdmin(admin admin) {
		int i = adminMapper.updateByPrimaryKeySelective(admin);
		if(i != 1){
			return false;
		}
		return true;
	}

	@Override
	public boolean imageUpload(String imgpath, Integer adminId) {
		//判断是否上传成功
		boolean isupload = true;
		if(StringUtils.isNotBlank(ObjectUtils.toString(imgpath))
				&& StringUtils.isNotBlank(ObjectUtils.toString(adminId))) {
			//判断id是否存在
			admin admin = adminMapper.selectByPrimaryKey(adminId);
			if(StringUtils.isNotBlank(ObjectUtils.toString(admin))){
				if(!admin.getAdminHeader().equals("")) {
					//如果管理员有头像则删除管理员原来头像
					//把数据库头像访问路径分割成两部分
					String[] adminHeaders = admin.getAdminHeader().split("8181/");
					//获取管理员头像
					String adminHeader = adminHeaders[1];
					System.out.println(adminHeader);
					File delFile = new File("/usr/tomcat/images/"+adminHeader);
				       if(delFile.isFile() && delFile.exists()) {
				           delFile.delete();
				           System.out.println("服务器文件删除成功");
				       }else {
				    	   System.out.println("服务器文件删除失败");
				     }
				}
				admin.setAdminHeader(imgpath);
				adminMapper.updateByPrimaryKeySelective(admin);
			}else {
				isupload = false;
				System.out.println("管理员不存在");
			}
		}else{
			isupload = false;
			System.out.println("id或者头像路径为空");
		}
		return isupload;
	}

	/**
	 * 根据管理员id查询管理员所拥有的的角色和所拥有的的权限
	 * @param adminId
	 * @return
	 */
	@Override
	public Map<String, Object> findAdminByAdminId(Integer adminId) {


		//根据管理员的id查询该管理员的角色信息
		List<cn.itcast.pojo.admin> adminRoleList = adminMapper.getAdminByAdminId(adminId);

		//把该管理员所拥有的角色存到set中
		HashSet<role> roleSet = new HashSet<>();
		for (cn.itcast.pojo.admin admin1 : adminRoleList) {
			roleSet.add(admin1.getRoles().get(0));
		}

		ArrayList<Integer> roleIds = new ArrayList<>();
		//把管理员的所有角色id存到list中
		for (cn.itcast.pojo.admin admin1 : adminRoleList) {
			roleIds.add(admin1.getRoles().get(0).getRoleId());
		}

		HashSet<permission> permissionSet = new HashSet<>();
		//根据该管理员所有的角色id查询该管理员所拥有的的权限
		List<role> roles = roleMapper.getRoleByRoleIds(roleIds);

		//把该管理员所拥有的的权限存到set中
		for (role role : roles) {
			permissionSet.add(role.getPermissions().get(0));
		}

		HashMap<String, Object> map = new HashMap<>();
		map.put("roleSet",roleSet);
		map.put("permissionSet",permissionSet);

		return map;
	}

	/**
	 * 根据管理员登录用户名查询该管理员的信息
	 * @param adminNickName
	 * @return
	 */
	@Override
	public admin findAdminByNickName(String adminNickName) {
		adminExample adminExample = new adminExample();
		cn.itcast.pojo.adminExample.Criteria criteria = adminExample.createCriteria();
		criteria.andAdminNicknameEqualTo(adminNickName);
		List<admin> admins = adminMapper.selectByExample(adminExample);
		admin admin = admins.get(0);
		return admin;
	}

	/**
	 * 获取所有的管理员以及管理所拥有的角色信息
	 * @param map
	 * @return
	 */
	@Override
	public Map<String, Object> getAllAdmin(Map<String, String> map) {
		//获取前台传递的数据
		Integer page = Integer.parseInt(map.get("page"));
		Integer limit = Integer.parseInt(map.get("limit"));
		String adminNickName = map.get("adminNickName");
		String adminName = map.get("adminName");
		String adminPhone = map.get("adminPhone");
//		int adminState = Integer.parseInt(map.get("adminState"));

		//添加查询条件
		adminExample adminExample = new adminExample();
		cn.itcast.pojo.adminExample.Criteria criteria = adminExample.createCriteria();
		if (!adminNickName.isEmpty()){
			criteria.andAdminNicknameLike("%"+adminNickName+"%");
		}
		if(!adminName.isEmpty()){
			criteria.andAdminNameLike("%"+adminName+"%");
		}
		if(!adminPhone.isEmpty()){
			criteria.andAdminPhoneLike("%"+adminPhone+"%");
		}
//		if(!map.get("adminState").isEmpty()){
//			criteria.andAdminStateEqualTo(adminState);
//		}
		//获取总记录数
		int count = adminMapper.selectByExample(adminExample).size();
		//开始分页
		PageHelper.startPage(page,limit);
		List<admin> adminList = adminMapper.selectByExample(adminExample);

		//查询所有管理员的所拥有的角色
		for (admin admin : adminList) {
			//根据管理员的id查询管理员所有的角色id
			List<Integer> roleIds = adminMapper.getRoleIdsByAdminId(admin.getAdminId());
			//根据所有的角色id查询所有的角色信息
			if(!roleIds.isEmpty()){
				List<role> roles = roleMapper.getRolesByList(roleIds);
				admin.setRoles(roles);
			}
		}

		HashMap<String, Object> resultMap = new HashMap<>();
		resultMap.put("adminList",adminList);
		resultMap.put("count",count);
		return resultMap;
	}

	/**
	 * 判断该管理员的用户名是否存在，存在返回true，不存在返回false
	 * @param adminNickName
	 * @return
	 */
	@Override
	public Boolean isOrNotAdminNickName(String adminNickName) {
		adminExample adminExample = new adminExample();
		cn.itcast.pojo.adminExample.Criteria criteria = adminExample.createCriteria();
		criteria.andAdminNicknameEqualTo(adminNickName);
		List<admin> admins = adminMapper.selectByExample(adminExample);
		if(admins.isEmpty()){
			return false;
		}
		return true;
	}

	/**
	 * 增加管理员以及添加相应的角色
	 * @param admin
	 * @param roleIds
	 * @return
	 */
	@Override
	public Boolean addAdminAndRole(admin admin, int[] roleIds) {
		int i = adminMapper.insertSelective(admin);
		if(i != 1){
			return false;
		}

		//获取添加的管理员的id
		adminExample adminExample = new adminExample();
		cn.itcast.pojo.adminExample.Criteria criteria = adminExample.createCriteria();
		criteria.andAdminNicknameEqualTo(admin.getAdminNickname());
		Integer adminId = adminMapper.selectByExample(adminExample).get(0).getAdminId();

		//开始给管理员添加相应的角色
		for (int a = 0; a < roleIds.length; a++) {
			int c = adminMapper.addAdminAndRole(adminId,roleIds[a]);
			if(c != 1){
				return false;
			}
		}
		return true;
	}

	/**
	 * 修改管理员以及管理员的角色
	 * @param map
	 * @return
	 */
	@Override
	public Boolean updateAdminAndRole(Map<String, String> map) {
		admin admin = new admin();
		admin.setAdminId(Integer.parseInt(map.get("adminId")));
		admin.setAdminPassword(map.get("adminPassword"));
		admin.setAdminNickname(map.get("adminNickName"));
		admin.setAdminPhone(map.get("adminPhone"));
		admin.setAdminName(map.get("adminName"));
		admin.setUpdateTime(new Date());
		admin.setAdminAddress(map.get("adminAddress"));
		int i = adminMapper.updateByPrimaryKeySelective(admin);
		if(i != 1){
			return false;
		}

		int adminId = Integer.parseInt(map.get("adminId"));
		//先删除该管理员之前的所有的角色，然后再添加前台修改页面选择的角色
		int g = adminMapper.deleteAdminAndRole(adminId);
		//开始给管理员赋予相应的角色
		String roles = map.get("roleIds");
		log.debug(roles);
		String[] roleIds = {};
		roleIds = roles.split(",");
		ArrayList<Integer> ids = new ArrayList<>();
		for(i=0 ; i<roleIds.length ; i++){
			ids.add(Integer.parseInt(roleIds[i]));
		}

		for (Integer id : ids) {
			int a = adminMapper.addAdminAndRole(adminId,id);
			if(a != 1){
				return false;
			}
		}

		return true;
	}

	/**
	 * 删除该管理员以及该管理员拥有的角色
	 * @param map
	 * @return
	 */
	@Override
	public Boolean deleteAdmin(Map<String, String> map) {
		int adminId = Integer.parseInt(map.get("adminId"));
		int a = adminMapper.deleteByPrimaryKey(adminId);
		if (a != 1){
			return false;
		}
		return true;
	}

    @Override
    public Integer SavaAdmin(admin admin) {
        int addAdmin = adminMapper.insert(admin);
        return addAdmin;
    }


}
